package com.github.zuul.config;

import com.marcosbarbero.cloud.autoconfigure.zuul.ratelimit.config.RateLimitKeyGenerator;
import com.marcosbarbero.cloud.autoconfigure.zuul.ratelimit.config.properties.RateLimitProperties;
import com.marcosbarbero.cloud.autoconfigure.zuul.ratelimit.support.RateLimitUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.Route;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.StringJoiner;
import java.util.stream.Collectors;

/**
 * Created by IntelliJ IDEA.
 * user:wangj
 * date:2018/7/22
 * Time: 22:16
 */
public class CustomLimitKeyGenerator implements RateLimitKeyGenerator {

    @Autowired
    private  RateLimitProperties properties;
    @Autowired
    private  RateLimitUtils rateLimitUtils;
    private static final Logger logger=LoggerFactory.getLogger(CustomLimitKeyGenerator.class);

    @Override
    public String key(HttpServletRequest request, Route route, RateLimitProperties.Policy policy) {
        // 获取当前 policy 的索引
        int indexOf = properties.getPolicies(route.getId()).indexOf(policy);
        logger.info("----------------"+indexOf);
        final List<RateLimitProperties.Policy.Type> types = policy.getType().stream().map(RateLimitProperties.Policy.MatchType::getType).collect(Collectors.toList());
        final StringJoiner joiner = new StringJoiner(":");
        joiner.add(properties.getKeyPrefix());
        if (route != null) {
            joiner.add(route.getId());
        }
        if (!types.isEmpty()) {
            if (types.contains(RateLimitProperties.Policy.Type.URL) && route != null) {
                joiner.add(route.getPath());
            }
            if (types.contains(RateLimitProperties.Policy.Type.ORIGIN)) {
                joiner.add(rateLimitUtils.getRemoteAddress(request));
            }
            if (types.contains(RateLimitProperties.Policy.Type.USER)) {
                joiner.add(rateLimitUtils.getUser(request));
            }
        }
        // 添加索引
        joiner.add(String.valueOf(indexOf));
        return joiner.toString();

    }

    private void addMatcher(StringJoiner joiner, RateLimitProperties.Policy.MatchType matchType) {
        if (StringUtils.isNotEmpty(matchType.getMatcher())) {
            joiner.add(matchType.getMatcher());
        }
    }
}
